{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "524620c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.nbeats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15392f6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12fa25a4",
   "metadata": {},
   "source": [
    "# NBEATS"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "376a8a3a",
   "metadata": {},
   "source": [
    "The Neural Basis Expansion Analysis (`NBEATS`) is an `MLP`-based deep neural architecture with backward and forward residual links. The network has two variants: (1) in its interpretable configuration, `NBEATS` sequentially projects the signal into polynomials and harmonic basis to learn trend and seasonality components; (2) in its generic configuration, it substitutes the polynomial and harmonic basis for identity basis and larger network's depth. The Neural Basis Expansion Analysis with Exogenous (`NBEATSx`), incorporates projections to exogenous temporal variables available at the time of the prediction.\n",
    "\n",
    "This method proved state-of-the-art performance on the M3, M4, and Tourism Competition datasets, improving accuracy by 3% over the `ESRNN` M4 competition winner.\n",
    "\n",
    "**References**<br>\n",
    "-[Boris N. Oreshkin, Dmitri Carpov, Nicolas Chapados, Yoshua Bengio (2019). \"N-BEATS: Neural basis expansion analysis for interpretable time series forecasting\".](https://arxiv.org/abs/1905.10437)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bddd17a6",
   "metadata": {},
   "source": [
    "![Figure 1. Neural Basis Expansion Analysis.](imgs_models/nbeats.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44065066-e72a-431f-938f-1528adef9fe8",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "import warnings\n",
    "from typing import Tuple, Optional\n",
    "\n",
    "import numpy as np\n",
    "from numpy.polynomial.legendre import Legendre\n",
    "from numpy.polynomial.chebyshev import Chebyshev\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from scipy.interpolate import BSpline\n",
    "\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "from neuralforecast.common._base_model import BaseModel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a77bb35",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.utils import generate_series\n",
    "from neuralforecast.common._model_checks import check_model\n",
    "\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3b21a80",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "def generate_legendre_basis(length, n_basis):\n",
    "    \"\"\"\n",
    "    Generates Legendre polynomial basis functions.\n",
    "\n",
    "    Parameters:\n",
    "    - n_points (int): Number of data points.\n",
    "    - n_functions (int): Number of basis functions to generate.\n",
    "\n",
    "    Returns:\n",
    "    - legendre_basis (ndarray): An array of Legendre basis functions.\n",
    "    \"\"\"\n",
    "    x = np.linspace(-1, 1, length)  # Legendre polynomials are defined on [-1, 1]\n",
    "    legendre_basis = np.zeros((length, n_basis))\n",
    "    for i in range(n_basis):\n",
    "        # Legendre polynomial of degree i\n",
    "        P_i = Legendre.basis(i)\n",
    "        legendre_basis[:, i] = P_i(x)\n",
    "    return legendre_basis\n",
    "\n",
    "def generate_polynomial_basis(length, n_basis):\n",
    "    \"\"\"\n",
    "    Generates standard polynomial basis functions.\n",
    "\n",
    "    Parameters:\n",
    "    - n_points (int): Number of data points.\n",
    "    - n_functions (int): Number of polynomial functions to generate.\n",
    "\n",
    "    Returns:\n",
    "    - poly_basis (ndarray): An array of polynomial basis functions.\n",
    "    \"\"\"\n",
    "    return np.concatenate([np.power(np.arange(length, dtype=float) / length, i)[None, :]\n",
    "                                    for i in range(n_basis)]).T\n",
    "\n",
    "\n",
    "def generate_changepoint_basis(length, n_basis):\n",
    "    \"\"\"\n",
    "    Generates changepoint basis functions with automatically spaced changepoints.\n",
    "\n",
    "    Parameters:\n",
    "    - n_points (int): Number of data points.\n",
    "    - n_functions (int): Number of changepoint functions to generate.\n",
    "\n",
    "    Returns:\n",
    "    - changepoint_basis (ndarray): An array of changepoint basis functions.\n",
    "    \"\"\"\n",
    "    x = np.linspace(0, 1, length)[:, None]  # Shape: (length, 1)\n",
    "    changepoint_locations = np.linspace(0, 1, n_basis + 1)[1:][None, :]  # Shape: (1, n_basis)\n",
    "    return np.maximum(0, x - changepoint_locations)\n",
    "\n",
    "def generate_piecewise_linear_basis(length, n_basis):\n",
    "    \"\"\"\n",
    "    Generates piecewise linear basis functions (linear splines).\n",
    "\n",
    "    Parameters:\n",
    "    - n_points (int): Number of data points.\n",
    "    - n_functions (int): Number of piecewise linear basis functions to generate.\n",
    "\n",
    "    Returns:\n",
    "    - pw_linear_basis (ndarray): An array of piecewise linear basis functions.\n",
    "    \"\"\"\n",
    "    x = np.linspace(0, 1, length)\n",
    "    knots = np.linspace(0, 1, n_basis+1)\n",
    "    pw_linear_basis = np.zeros((length, n_basis))\n",
    "    for i in range(1, n_basis):\n",
    "        pw_linear_basis[:, i] = np.maximum(0, np.minimum((x - knots[i-1]) / (knots[i] - knots[i-1]), (knots[i+1] - x) / (knots[i+1] - knots[i])))\n",
    "    return pw_linear_basis\n",
    "\n",
    "def generate_linear_hat_basis(length, n_basis):\n",
    "    x = np.linspace(0, 1, length)[:, None]  # Shape: (length, 1)\n",
    "    centers = np.linspace(0, 1, n_basis)[None, :]  # Shape: (1, n_basis)\n",
    "    width = 1.0 / (n_basis - 1)\n",
    "    \n",
    "    # Create triangular functions using piecewise linear equations\n",
    "    return np.maximum(0, 1 - np.abs(x - centers) / width)\n",
    "\n",
    "def generate_spline_basis(length, n_basis):\n",
    "    \"\"\"\n",
    "    Generates cubic spline basis functions.\n",
    "\n",
    "    Parameters:\n",
    "    - n_points (int): Number of data points.\n",
    "    - n_functions (int): Number of basis functions.\n",
    "\n",
    "    Returns:\n",
    "    - spline_basis (ndarray): An array of cubic spline basis functions.\n",
    "    \"\"\"\n",
    "    if n_basis < 4:\n",
    "        raise ValueError(f\"To use the spline basis, n_basis must be set to 4 or more. Current value is {n_basis}\")\n",
    "    x = np.linspace(0, 1, length)\n",
    "    knots = np.linspace(0, 1, n_basis - 2)\n",
    "    t = np.concatenate(([0, 0, 0], knots, [1, 1, 1]))\n",
    "    degree = 3\n",
    "    # Create basis coefficient matrix once\n",
    "    coefficients = np.eye(n_basis)\n",
    "    # Create single BSpline object with all coefficients\n",
    "    spline = BSpline(t, coefficients.T, degree)\n",
    "    return spline(x)\n",
    "\n",
    "def generate_chebyshev_basis(length, n_basis):\n",
    "    \"\"\"\n",
    "    Generates Chebyshev polynomial basis functions.\n",
    "\n",
    "    Parameters:\n",
    "    - n_points (int): Number of data points.\n",
    "    - n_functions (int): Number of Chebyshev polynomials to generate.\n",
    "\n",
    "    Returns:\n",
    "    - chebyshev_basis (ndarray): An array of Chebyshev polynomial basis functions.\n",
    "    \"\"\"\n",
    "    x = np.linspace(-1, 1, length)\n",
    "    chebyshev_basis = np.zeros((length, n_basis))\n",
    "    for i in range(n_basis):\n",
    "        T_i = Chebyshev.basis(i)\n",
    "        chebyshev_basis[:, i] = T_i(x)\n",
    "    return chebyshev_basis\n",
    "\n",
    "def get_basis(length, n_basis, basis):\n",
    "    basis_dict = {\n",
    "        'legendre': generate_legendre_basis,\n",
    "        'polynomial': generate_polynomial_basis,\n",
    "        'changepoint': generate_changepoint_basis,\n",
    "        'piecewise_linear': generate_piecewise_linear_basis,\n",
    "        'linear_hat': generate_linear_hat_basis,\n",
    "        'spline': generate_spline_basis,\n",
    "        'chebyshev': generate_chebyshev_basis\n",
    "    }\n",
    "    return basis_dict[basis](length, n_basis+1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b7a9fae-2c29-47e2-874e-ca1f20bf7040",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "class IdentityBasis(nn.Module):\n",
    "    def __init__(self, backcast_size: int, forecast_size: int,\n",
    "                 out_features: int=1):\n",
    "        super().__init__()\n",
    "        self.out_features = out_features\n",
    "        self.forecast_size = forecast_size\n",
    "        self.backcast_size = backcast_size\n",
    " \n",
    "    def forward(self, theta: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "        backcast = theta[:, :self.backcast_size]\n",
    "        forecast = theta[:, self.backcast_size:]\n",
    "        forecast = forecast.reshape(len(forecast), -1, self.out_features)\n",
    "        return backcast, forecast\n",
    "\n",
    "class TrendBasis(nn.Module):\n",
    "    def __init__(self, \n",
    "                 n_basis: int,\n",
    "                 backcast_size: int,\n",
    "                 forecast_size: int,\n",
    "                 out_features: int=1,\n",
    "                 basis='polynomial'):\n",
    "        super().__init__()\n",
    "        self.out_features = out_features\n",
    "        self.backcast_basis = nn.Parameter(\n",
    "            torch.tensor(get_basis(backcast_size, n_basis, basis).T, dtype=torch.float32), requires_grad=False)\n",
    "        self.forecast_basis = nn.Parameter(\n",
    "            torch.tensor(get_basis(forecast_size, n_basis, basis).T, dtype=torch.float32), requires_grad=False)\n",
    "\n",
    "    def forward(self, theta: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "        polynomial_size = self.forecast_basis.shape[0] # [polynomial_size, L+H]\n",
    "        backcast_theta = theta[:, :polynomial_size]\n",
    "        forecast_theta = theta[:, polynomial_size:]\n",
    "        forecast_theta = forecast_theta.reshape(len(forecast_theta),polynomial_size,-1)\n",
    "        backcast = torch.einsum('bp,pt->bt', backcast_theta, self.backcast_basis)\n",
    "        forecast = torch.einsum('bpq,pt->btq', forecast_theta, self.forecast_basis)\n",
    "        return backcast, forecast\n",
    "\n",
    "class SeasonalityBasis(nn.Module):\n",
    "    def __init__(self, \n",
    "                 harmonics: int, \n",
    "                 backcast_size: int, \n",
    "                 forecast_size: int,\n",
    "                 out_features: int=1):\n",
    "        super().__init__()\n",
    "        self.out_features = out_features\n",
    "        frequency = np.append(np.zeros(1, dtype=float),\n",
    "                                        np.arange(harmonics, harmonics / 2 * forecast_size,\n",
    "                                                    dtype=float) / harmonics)[None, :]\n",
    "        backcast_grid = -2 * np.pi * (\n",
    "                np.arange(backcast_size, dtype=float)[:, None] / forecast_size) * frequency\n",
    "        forecast_grid = 2 * np.pi * (\n",
    "                np.arange(forecast_size, dtype=float)[:, None] / forecast_size) * frequency\n",
    "\n",
    "        backcast_cos_template = torch.tensor(np.transpose(np.cos(backcast_grid)), dtype=torch.float32)\n",
    "        backcast_sin_template = torch.tensor(np.transpose(np.sin(backcast_grid)), dtype=torch.float32)\n",
    "        backcast_template = torch.cat([backcast_cos_template, backcast_sin_template], dim=0)\n",
    "\n",
    "        forecast_cos_template = torch.tensor(np.transpose(np.cos(forecast_grid)), dtype=torch.float32)\n",
    "        forecast_sin_template = torch.tensor(np.transpose(np.sin(forecast_grid)), dtype=torch.float32)\n",
    "        forecast_template = torch.cat([forecast_cos_template, forecast_sin_template], dim=0)\n",
    "\n",
    "        self.backcast_basis = nn.Parameter(backcast_template, requires_grad=False)\n",
    "        self.forecast_basis = nn.Parameter(forecast_template, requires_grad=False)\n",
    "\n",
    "    def forward(self, theta: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "        harmonic_size = self.forecast_basis.shape[0] # [harmonic_size, L+H]\n",
    "        backcast_theta = theta[:, :harmonic_size]\n",
    "        forecast_theta = theta[:, harmonic_size:]\n",
    "        forecast_theta = forecast_theta.reshape(len(forecast_theta),harmonic_size,-1)\n",
    "        backcast = torch.einsum('bp,pt->bt', backcast_theta, self.backcast_basis)\n",
    "        forecast = torch.einsum('bpq,pt->btq', forecast_theta, self.forecast_basis)\n",
    "        return backcast, forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17382790-7d84-4a89-959b-5676afa46392",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "ACTIVATIONS = ['ReLU',\n",
    "               'Softplus',\n",
    "               'Tanh',\n",
    "               'SELU',\n",
    "               'LeakyReLU',\n",
    "               'PReLU',\n",
    "               'Sigmoid']\n",
    "\n",
    "class NBEATSBlock(nn.Module):\n",
    "    \"\"\"\n",
    "    N-BEATS block which takes a basis function as an argument.\n",
    "    \"\"\"\n",
    "    def __init__(self, \n",
    "                 input_size: int,\n",
    "                 n_theta: int, \n",
    "                 mlp_units: list,\n",
    "                 basis: nn.Module, \n",
    "                 dropout_prob: float, \n",
    "                 activation: str):\n",
    "        super().__init__()\n",
    "\n",
    "        self.dropout_prob = dropout_prob\n",
    "        \n",
    "        assert activation in ACTIVATIONS, f'{activation} is not in {ACTIVATIONS}'\n",
    "        activ = getattr(nn, activation)()\n",
    "        \n",
    "        hidden_layers = [nn.Linear(in_features=input_size, \n",
    "                                   out_features=mlp_units[0][0])]\n",
    "        for layer in mlp_units:\n",
    "            hidden_layers.append(nn.Linear(in_features=layer[0], \n",
    "                                           out_features=layer[1]))\n",
    "            hidden_layers.append(activ)\n",
    "\n",
    "            if self.dropout_prob>0:\n",
    "                raise NotImplementedError('dropout')\n",
    "\n",
    "        output_layer = [nn.Linear(in_features=mlp_units[-1][1], out_features=n_theta)]\n",
    "        layers = hidden_layers + output_layer\n",
    "        self.layers = nn.Sequential(*layers)\n",
    "        self.basis = basis\n",
    "\n",
    "    def forward(self, insample_y: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n",
    "        # Compute local projection weights and projection\n",
    "        theta = self.layers(insample_y)\n",
    "        backcast, forecast = self.basis(theta)\n",
    "        return backcast, forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be997aeb-778f-442d-a97a-ff47de2deab6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class NBEATS(BaseModel):\n",
    "    \"\"\" NBEATS\n",
    "\n",
    "    The Neural Basis Expansion Analysis for Time Series (NBEATS), is a simple and yet\n",
    "    effective architecture, it is built with a deep stack of MLPs with the doubly \n",
    "    residual connections. It has a generic and interpretable architecture depending\n",
    "    on the blocks it uses. Its interpretable architecture is recommended for scarce\n",
    "    data settings, as it regularizes its predictions through projections unto harmonic\n",
    "    and trend basis well-suited for most forecasting tasks.\n",
    "\n",
    "    **Parameters:**<br>\n",
    "    `h`: int, forecast horizon.<br>\n",
    "    `input_size`: int, considered autorregresive inputs (lags), y=[1,2,3,4] input_size=2 -> lags=[1,2].<br>\n",
    "    `n_harmonics`: int, Number of harmonic terms for seasonality stack type. Note that len(n_harmonics) = len(stack_types). Note that it will only be used if a seasonality stack is used.<br>\n",
    "    `n_polynomials`: int, DEPRECATED - polynomial degree for trend stack. Note that len(n_polynomials) = len(stack_types). Note that it will only be used if a trend stack is used.<br>\n",
    "    `basis`: str, Type of basis function to use in the trend stack. Choose one from ['legendre', 'polynomial', 'changepoint', 'piecewise_linear', 'linear_hat', 'spline', 'chebyshev']<br>\n",
    "    `n_basis`: int, the degree of the basis function for the trend stack. Note that it will only be used if a trend stack is used.<br>\n",
    "    `stack_types`: List[str], List of stack types. Subset from ['seasonality', 'trend', 'identity'].<br>\n",
    "    `n_blocks`: List[int], Number of blocks for each stack. Note that len(n_blocks) = len(stack_types).<br>\n",
    "    `mlp_units`: List[List[int]], Structure of hidden layers for each stack type. Each internal list should contain the number of units of each hidden layer. Note that len(n_hidden) = len(stack_types).<br>\n",
    "    `dropout_prob_theta`: float, Float between (0, 1). Dropout for N-BEATS basis.<br>\n",
    "    `activation`: str, activation from ['ReLU', 'Softplus', 'Tanh', 'SELU', 'LeakyReLU', 'PReLU', 'Sigmoid'].<br>\n",
    "    `shared_weights`: bool, If True, all blocks within each stack will share parameters. <br>\n",
    "    `loss`: PyTorch module, instantiated train loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `valid_loss`: PyTorch module=`loss`, instantiated valid loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `max_steps`: int=1000, maximum number of training steps.<br>\n",
    "    `learning_rate`: float=1e-3, Learning rate between (0, 1).<br>\n",
    "    `num_lr_decays`: int=3, Number of learning rate decays, evenly distributed across max_steps.<br>\n",
    "    `early_stop_patience_steps`: int=-1, Number of validation iterations before early stopping.<br>\n",
    "    `val_check_steps`: int=100, Number of training steps between every validation loss check.<br>\n",
    "    `batch_size`: int=32, number of different series in each batch.<br>\n",
    "    `valid_batch_size`: int=None, number of different series in each validation and test batch, if None uses batch_size.<br>\n",
    "    `windows_batch_size`: int=1024, number of windows to sample in each training batch, default uses all.<br>\n",
    "    `inference_windows_batch_size`: int=-1, number of windows to sample in each inference batch, -1 uses all.<br>\n",
    "    `start_padding_enabled`: bool=False, if True, the model will pad the time series with zeros at the beginning, by input size.<br>\n",
    "    `step_size`: int=1, step size between each window of temporal data.<br>\n",
    "    `scaler_type`: str='identity', type of scaler for temporal inputs normalization see [temporal scalers](https://nixtla.github.io/neuralforecast/common.scalers.html).<br>\n",
    "    `random_seed`: int, random_seed for pytorch initializer and numpy generators.<br>\n",
    "    `drop_last_loader`: bool=False, if True `TimeSeriesDataLoader` drops last non-full batch.<br>\n",
    "    `alias`: str, optional,  Custom name of the model.<br>\n",
    "    `optimizer`: Subclass of 'torch.optim.Optimizer', optional, user specified optimizer instead of the default choice (Adam).<br>\n",
    "    `optimizer_kwargs`: dict, optional, list of parameters used by the user specified `optimizer`.<br>\n",
    "    `lr_scheduler`: Subclass of 'torch.optim.lr_scheduler.LRScheduler', optional, user specified lr_scheduler instead of the default choice (StepLR).<br>\n",
    "    `lr_scheduler_kwargs`: dict, optional, list of parameters used by the user specified `lr_scheduler`.<br>\n",
    "    `dataloader_kwargs`: dict, optional, list of parameters passed into the PyTorch Lightning dataloader by the `TimeSeriesDataLoader`. <br>\n",
    "    `**trainer_kwargs`: int,  keyword trainer arguments inherited from [PyTorch Lighning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).<br>\n",
    "\n",
    "    **References:**<br>\n",
    "    -[Boris N. Oreshkin, Dmitri Carpov, Nicolas Chapados, Yoshua Bengio (2019). \n",
    "    \"N-BEATS: Neural basis expansion analysis for interpretable time series forecasting\".](https://arxiv.org/abs/1905.10437)\n",
    "    \"\"\"\n",
    "    # Class attributes\n",
    "    EXOGENOUS_FUTR = False\n",
    "    EXOGENOUS_HIST = False\n",
    "    EXOGENOUS_STAT = False\n",
    "    MULTIVARIATE = False    # If the model produces multivariate forecasts (True) or univariate (False)\n",
    "    RECURRENT = False       # If the model produces forecasts recursively (True) or direct (False)\n",
    "    \n",
    "    def __init__(self,\n",
    "                 h,\n",
    "                 input_size,\n",
    "                 n_harmonics: int = 2,\n",
    "                 n_polynomials: Optional[int] = None,\n",
    "                 n_basis: int = 2,\n",
    "                 basis: str = 'polynomial',\n",
    "                 stack_types: list = ['identity', 'trend', 'seasonality'],\n",
    "                 n_blocks: list = [1, 1, 1],\n",
    "                 mlp_units: list = 3 * [[512, 512]],\n",
    "                 dropout_prob_theta: float = 0.,\n",
    "                 activation: str = 'ReLU',\n",
    "                 shared_weights: bool = False,                 \n",
    "                 loss = MAE(),\n",
    "                 valid_loss = None,\n",
    "                 max_steps: int = 1000,\n",
    "                 learning_rate: float = 1e-3,\n",
    "                 num_lr_decays: int = 3,\n",
    "                 early_stop_patience_steps: int =-1,\n",
    "                 val_check_steps: int = 100,\n",
    "                 batch_size: int = 32,\n",
    "                 valid_batch_size: Optional[int] = None,\n",
    "                 windows_batch_size: int = 1024,\n",
    "                 inference_windows_batch_size: int = -1,\n",
    "                 start_padding_enabled = False,\n",
    "                 step_size: int = 1,\n",
    "                 scaler_type: str ='identity',\n",
    "                 random_seed: int = 1,\n",
    "                 drop_last_loader: bool = False,\n",
    "                 alias: Optional[str] = None,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 lr_scheduler = None,\n",
    "                 lr_scheduler_kwargs = None,\n",
    "                 dataloader_kwargs = None,\n",
    "                 **trainer_kwargs):\n",
    "        \n",
    "        # Protect horizon collapsed seasonality and trend NBEATSx-i basis\n",
    "        if h == 1 and ((\"seasonality\" in stack_types) or (\"trend\" in stack_types)):\n",
    "            raise Exception(\n",
    "                \"Horizon `h=1` incompatible with `seasonality` or `trend` in stacks\"\n",
    "            )\n",
    "\n",
    "        # Inherit BaseWindows class\n",
    "        super(NBEATS, self).__init__(h=h,\n",
    "                                     input_size=input_size,\n",
    "                                     loss=loss,\n",
    "                                     valid_loss=valid_loss,\n",
    "                                     max_steps=max_steps,\n",
    "                                     learning_rate=learning_rate,\n",
    "                                     num_lr_decays=num_lr_decays,\n",
    "                                     early_stop_patience_steps=early_stop_patience_steps,\n",
    "                                     val_check_steps=val_check_steps,\n",
    "                                     batch_size=batch_size,\n",
    "                                     windows_batch_size=windows_batch_size,\n",
    "                                     valid_batch_size=valid_batch_size,\n",
    "                                     inference_windows_batch_size=inference_windows_batch_size,\n",
    "                                     start_padding_enabled=start_padding_enabled,\n",
    "                                     step_size=step_size,\n",
    "                                     scaler_type=scaler_type,\n",
    "                                     drop_last_loader=drop_last_loader,\n",
    "                                     alias=alias,\n",
    "                                     random_seed=random_seed,\n",
    "                                     optimizer=optimizer,\n",
    "                                     optimizer_kwargs=optimizer_kwargs,\n",
    "                                     lr_scheduler=lr_scheduler,\n",
    "                                     lr_scheduler_kwargs=lr_scheduler_kwargs,\n",
    "                                     dataloader_kwargs=dataloader_kwargs,\n",
    "                                     **trainer_kwargs)\n",
    "\n",
    "        # Raise deprecation warning\n",
    "        if n_polynomials is not None:\n",
    "            warnings.warn(\n",
    "                \"The parameter n_polynomials will be deprecated in favor of n_basis and basis and it is currently ignored.\\n\"\n",
    "                \"The basis parameter defines the basis function to be used in the trend stack.\\n\"\n",
    "                \"The n_basis defines the degree of the basis function used in the trend stack.\",\n",
    "                DeprecationWarning\n",
    "            )\n",
    "        \n",
    "        # Architecture\n",
    "        blocks = self.create_stack(h=h,\n",
    "                                   input_size=input_size,\n",
    "                                   stack_types=stack_types, \n",
    "                                   n_blocks=n_blocks,\n",
    "                                   mlp_units=mlp_units,\n",
    "                                   dropout_prob_theta=dropout_prob_theta,\n",
    "                                   activation=activation,\n",
    "                                   shared_weights=shared_weights,\n",
    "                                   n_harmonics=n_harmonics,\n",
    "                                   n_basis=n_basis,\n",
    "                                   basis_type=basis)\n",
    "        self.blocks = torch.nn.ModuleList(blocks)\n",
    "\n",
    "    def create_stack(self, \n",
    "                     stack_types, \n",
    "                     n_blocks, \n",
    "                     input_size, \n",
    "                     h, \n",
    "                     mlp_units, \n",
    "                     dropout_prob_theta, \n",
    "                     activation, \n",
    "                     shared_weights,\n",
    "                     n_harmonics, \n",
    "                     n_basis, \n",
    "                     basis_type):                     \n",
    "\n",
    "        block_list = []\n",
    "        for i in range(len(stack_types)):\n",
    "            for block_id in range(n_blocks[i]):\n",
    "\n",
    "                # Shared weights\n",
    "                if shared_weights and block_id>0:\n",
    "                    nbeats_block = block_list[-1]\n",
    "                else:\n",
    "                    if stack_types[i] == 'seasonality':\n",
    "                        n_theta = 2 * (self.loss.outputsize_multiplier + 1) * \\\n",
    "                                  int(np.ceil(n_harmonics / 2 * h) - (n_harmonics - 1))\n",
    "                        basis = SeasonalityBasis(harmonics=n_harmonics,\n",
    "                                                 backcast_size=input_size,\n",
    "                                                 forecast_size=h,\n",
    "                                                 out_features=self.loss.outputsize_multiplier)\n",
    "\n",
    "                    elif stack_types[i] == 'trend':\n",
    "                        n_theta = (self.loss.outputsize_multiplier + 1) * (n_basis + 1)\n",
    "                        basis = TrendBasis(n_basis=n_basis,\n",
    "                                           backcast_size=input_size,\n",
    "                                           forecast_size=h,\n",
    "                                           out_features=self.loss.outputsize_multiplier,\n",
    "                                           basis=basis_type)\n",
    "\n",
    "                    elif stack_types[i] == 'identity':\n",
    "                        n_theta = input_size + self.loss.outputsize_multiplier * h\n",
    "                        basis = IdentityBasis(backcast_size=input_size, forecast_size=h,\n",
    "                                              out_features=self.loss.outputsize_multiplier)\n",
    "                    else:\n",
    "                        raise ValueError(f'Block type {stack_types[i]} not found!')\n",
    "\n",
    "                    nbeats_block = NBEATSBlock(input_size=input_size,\n",
    "                                               n_theta=n_theta,\n",
    "                                               mlp_units=mlp_units,\n",
    "                                               basis=basis,\n",
    "                                               dropout_prob=dropout_prob_theta,\n",
    "                                               activation=activation)\n",
    "\n",
    "                # Select type of evaluation and apply it to all layers of block\n",
    "                block_list.append(nbeats_block)\n",
    "                \n",
    "        return block_list\n",
    "\n",
    "    def forward(self, windows_batch):\n",
    "        \n",
    "        # Parse windows_batch\n",
    "        insample_y    = windows_batch['insample_y'].squeeze(-1)\n",
    "        insample_mask = windows_batch['insample_mask'].squeeze(-1)\n",
    "\n",
    "        # NBEATS' forward\n",
    "        residuals = insample_y.flip(dims=(-1,)) # backcast init\n",
    "        insample_mask = insample_mask.flip(dims=(-1,))\n",
    "        \n",
    "        forecast = insample_y[:, -1:, None] # Level with Naive1\n",
    "        block_forecasts = [ forecast.repeat(1, self.h, 1) ]\n",
    "        for i, block in enumerate(self.blocks):\n",
    "            backcast, block_forecast = block(insample_y=residuals)\n",
    "            residuals = (residuals - backcast) * insample_mask\n",
    "            forecast = forecast + block_forecast\n",
    "\n",
    "            if self.decompose_forecast:\n",
    "                block_forecasts.append(block_forecast)               \n",
    "\n",
    "        if self.decompose_forecast:\n",
    "            # (n_batch, n_blocks, h, out_features)\n",
    "            block_forecasts = torch.stack(block_forecasts)\n",
    "            block_forecasts = block_forecasts.permute(1,0,2,3)\n",
    "            block_forecasts = block_forecasts.squeeze(-1) # univariate output\n",
    "            return block_forecasts\n",
    "        else:\n",
    "            return forecast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c57a831f-94bc-4616-b579-c114c3fc57c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NBEATS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9013b63-f65b-4a92-913c-b696e6e69914",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NBEATS.fit, name='NBEATS.fit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a66184ee-7a71-4598-976c-c79b83089a6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(NBEATS.predict, name='NBEATS.predict')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8de78f60",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# Unit tests for models\n",
    "logging.getLogger(\"pytorch_lightning\").setLevel(logging.ERROR)\n",
    "logging.getLogger(\"lightning_fabric\").setLevel(logging.ERROR)\n",
    "with warnings.catch_warnings():\n",
    "    warnings.simplefilter(\"ignore\")\n",
    "    check_model(NBEATS, [\"airpassengers\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2bf3e1d-2935-4503-afb6-fe3d6f52622c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast.tsdataset import TimeSeriesDataset\n",
    "from neuralforecast.utils import AirPassengersDF as Y_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6bb4c6c6-ef60-47c9-8c90-4002e68410d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "Y_train_df = Y_df[Y_df.ds<Y_df['ds'].values[-12]] # 132 train\n",
    "Y_test_df = Y_df[Y_df.ds>=Y_df['ds'].values[-12]]   # 12 test\n",
    "\n",
    "dataset, *_ = TimeSeriesDataset.from_df(df = Y_train_df)\n",
    "nbeats = NBEATS(h=12, input_size=24, windows_batch_size=None, \n",
    "                stack_types=['identity', 'trend', 'seasonality'], max_steps=1)\n",
    "nbeats.fit(dataset=dataset)\n",
    "y_hat = nbeats.predict(dataset=dataset)\n",
    "Y_test_df['N-BEATS'] = y_hat\n",
    "\n",
    "pd.concat([Y_train_df, Y_test_df]).drop('unique_id', axis=1).set_index('ds').plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db94b63e-d82c-423f-8f75-184ae285904d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "#test we recover the same forecast\n",
    "y_hat2 = nbeats.predict(dataset=dataset)\n",
    "test_eq(y_hat, y_hat2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46090447-8e67-4f08-8a3d-9547183983f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "#test no leakage with test_size\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_df)\n",
    "model = NBEATS(input_size=24, h=12, \n",
    "               windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, test_size=12)\n",
    "y_hat_test = model.predict(dataset=dataset, step_size=1)\n",
    "np.testing.assert_almost_equal(y_hat, y_hat_test, decimal=4)\n",
    "#test we recover the same forecast\n",
    "y_hat_test2 = model.predict(dataset=dataset, step_size=1)\n",
    "test_eq(y_hat_test, y_hat_test2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0298fce5-eb13-40dc-9964-b026fd2a8928",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# test validation step\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_train_df)\n",
    "model = NBEATS(input_size=24, h=12, windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, val_size=12)\n",
    "y_hat_w_val = model.predict(dataset=dataset)\n",
    "Y_test_df['N-BEATS'] = y_hat_w_val\n",
    "\n",
    "pd.concat([Y_train_df, Y_test_df]).drop('unique_id', axis=1).set_index('ds').plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f987ed0-ee6e-4f66-bd8f-96acc6fbd56c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# test no leakage with test_size and val_size\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_train_df)\n",
    "model = NBEATS(input_size=24, h=12, windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, val_size=12)\n",
    "y_hat_w_val = model.predict(dataset=dataset)\n",
    "\n",
    "dataset, *_ = TimeSeriesDataset.from_df(Y_df)\n",
    "model = NBEATS(input_size=24, h=12, windows_batch_size=None, max_steps=1)\n",
    "model.fit(dataset=dataset, val_size=12, test_size=12)\n",
    "\n",
    "y_hat_test_w_val = model.predict(dataset=dataset, step_size=1)\n",
    "\n",
    "np.testing.assert_almost_equal(y_hat_test_w_val, y_hat_w_val, decimal=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba4e41b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# qualitative decomposition evaluation\n",
    "y_hat = model.decompose(dataset=dataset)\n",
    "\n",
    "fig, ax = plt.subplots(5, 1, figsize=(10, 15))\n",
    "\n",
    "ax[0].plot(Y_test_df['y'].values, label='True', color=\"#9C9DB2\", linewidth=4)\n",
    "ax[0].plot(y_hat.sum(axis=1).flatten(), label='Forecast', color=\"#7B3841\")\n",
    "ax[0].grid()\n",
    "ax[0].legend(prop={'size': 20})\n",
    "for label in (ax[0].get_xticklabels() + ax[0].get_yticklabels()):\n",
    "    label.set_fontsize(18)\n",
    "ax[0].set_ylabel('y', fontsize=20)\n",
    "\n",
    "ax[1].plot(y_hat[0,0], label='level', color=\"#7B3841\")\n",
    "ax[1].grid()\n",
    "ax[1].set_ylabel('Level', fontsize=20)\n",
    "\n",
    "ax[2].plot(y_hat[0,1], label='stack1', color=\"#7B3841\")\n",
    "ax[2].grid()\n",
    "ax[2].set_ylabel('Identity', fontsize=20)\n",
    "\n",
    "ax[3].plot(y_hat[0,2], label='stack2', color=\"#D9AE9E\")\n",
    "ax[3].grid()\n",
    "ax[3].set_ylabel('Trend', fontsize=20)\n",
    "\n",
    "ax[4].plot(y_hat[0,3], label='stack3', color=\"#D9AE9E\")\n",
    "ax[4].grid()\n",
    "ax[4].set_ylabel('Seasonality', fontsize=20)\n",
    "\n",
    "ax[4].set_xlabel('Prediction \\u03C4 \\u2208 {t+1,..., t+H}', fontsize=20)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdc17eef",
   "metadata": {},
   "source": [
    "## Usage Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3017c43a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import NBEATS\n",
    "from neuralforecast.losses.pytorch import DistributionLoss\n",
    "from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic\n",
    "\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "model = NBEATS(h=12, input_size=24,\n",
    "               basis='changepoint',\n",
    "               n_basis=2,\n",
    "               loss=DistributionLoss(distribution='Poisson', level=[80, 90]),\n",
    "               stack_types = ['identity', 'trend', 'seasonality'],\n",
    "               max_steps=100,\n",
    "               val_check_steps=10,\n",
    "               early_stop_patience_steps=2)\n",
    "\n",
    "fcst = NeuralForecast(\n",
    "    models=[model],\n",
    "    freq='ME'\n",
    ")\n",
    "fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)\n",
    "forecasts = fcst.predict(futr_df=Y_test_df)\n",
    "\n",
    "# Plot quantile predictions\n",
    "Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds'])\n",
    "plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)\n",
    "plot_df = pd.concat([Y_train_df, plot_df])\n",
    "\n",
    "plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)\n",
    "plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')\n",
    "plt.plot(plot_df['ds'], plot_df['NBEATS-median'], c='blue', label='median')\n",
    "plt.fill_between(x=plot_df['ds'][-12:], \n",
    "                 y1=plot_df['NBEATS-lo-90'][-12:].values, \n",
    "                 y2=plot_df['NBEATS-hi-90'][-12:].values,\n",
    "                 alpha=0.4, label='level 90')\n",
    "plt.grid()\n",
    "plt.legend()\n",
    "plt.plot()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
